/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved.
 */

package com.huawei.idea.share;

import android.content.Context;

import com.huawei.idea.ideasharesdk.utils.LogUtil;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 全局异常捕获
 *
 * @author w00415409
 * @since 2021/2/10
 */
public class DemoExceptionHandler implements Thread.UncaughtExceptionHandler {
    private static final String TAG = DemoExceptionHandler.class.getSimpleName();

    private static final DemoExceptionHandler INSTANCE = new DemoExceptionHandler();

    private Thread.UncaughtExceptionHandler systemDefaultHandler;

    private Context context;

    private static final String FILE_NAME = "CrashError.log";

    private static String FILE_DIR = "";

    private static final long MAX_SIZE = 1024 * 3;

    public synchronized static DemoExceptionHandler getInstance() {
        return INSTANCE;
    }

    @Override
    public void uncaughtException(Thread t, Throwable e) {
        File file = new File(FILE_DIR, FILE_NAME);
        // 创建文件夹
        File parentDir = file.getParentFile();
        if (!parentDir.exists()) {
            file.mkdirs();
        }
        // 创建异常文件
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException exception) {
                LogUtil.info(TAG, exception);
            }
        }
        // 写入异常
        try (PrintWriter printWriter = new PrintWriter(file)) {
            e.printStackTrace(printWriter);
        } catch (IOException exception) {
            LogUtil.info(TAG, exception);
        }
    }

    /**
     * 初始化默认异常捕获
     *
     * @param context context
     * @param fileDir fileDir
     */
    public void init(Context context, String fileDir) {
        this.context = context;
        FILE_DIR = fileDir;
        // 获取默认异常处理器
        systemDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        // 将此类设为默认异常处理器
        Thread.setDefaultUncaughtExceptionHandler(this);
    }
}
